package pers.jg.rrsserver.controller

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.google.gson.GsonBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import pers.jg.rrsserver.entity.Goods
import pers.jg.rrsserver.entity.GoodsOrder
import pers.jg.rrsserver.entity.User
import pers.jg.rrsserver.mapper.GoodsMapper
import pers.jg.rrsserver.mapper.GoodsOrderMapper
import pers.jg.rrsserver.mapper.UserMapper
import pers.jg.rrsserver.service.SafeService
import java.sql.Timestamp
import java.time.Instant

@RestController
@CrossOrigin
class GoodsOrderController {

    @Autowired
    private lateinit var userMapper: UserMapper
    val dateFormat = "yyyy-MM-dd'T'HH:mm:sssZ"

    class GoodsOrderList {
        lateinit var goodsOrderList: ArrayList<GoodsOrder>
    }

    @Autowired
    private lateinit var goodsOrderMapper: GoodsOrderMapper

    @Autowired
    private lateinit var goodsMapper: GoodsMapper

    @Autowired
    private lateinit var safeService: SafeService

    open class Response {
        var result = ""
    }

    class ResponseWithGoodsOrder : Response() {
        lateinit var goodsOrder: GoodsOrder
        var inventory = 0
    }

    /**
     * 用户下单API
     * @param data 商品订单信息
     * @return result: ok(下单成功) | inventoryInsufficient(库存不足)
     * user: 下单成功的订单
     * inventory: 当前库存
     */
    @PostMapping("/api/placeAnOrder")
    fun placeAnOrder(
        @RequestBody data: String
    ): String {

        val res = ResponseWithGoodsOrder()
        val gson = GsonBuilder().setDateFormat(dateFormat).create()

        // 查询库存，若库存不足，拒绝下单
        val newGoodsOrder = gson.fromJson(data, GoodsOrder::class.java)
        val wrapper = QueryWrapper<Goods>().eq("id", newGoodsOrder.goodsId)
        val currentGoods = goodsMapper.selectOne(wrapper)
        if (currentGoods.inventory!! < newGoodsOrder.buyNum!!) {
            res.result = "inventoryInsufficient"
            res.inventory = currentGoods.inventory!!
            return gson.toJson(res)
        }
        //  库存充足，接收订单，上传数据库
        else {
            // 减去商品库存，增加商品销量
            currentGoods.inventory = currentGoods.inventory!! - newGoodsOrder.buyNum!!
            currentGoods.sales = currentGoods.sales!! + newGoodsOrder.buyNum!!
            val updateRes = goodsMapper.updateById(currentGoods)

            // 生成订单信息，上传数据库
            newGoodsOrder.id = safeService.createUUIDv4()
            newGoodsOrder.buyTime = Timestamp.from(Instant.now())
            goodsOrderMapper.insert(newGoodsOrder)
            res.result = "ok"
            res.inventory = currentGoods.inventory!!
            res.goodsOrder = newGoodsOrder
            return gson.toJson(res)
        }
    }

    @GetMapping("/api/getGoodsOrderList")
    fun getGoodsOrderList(
        @RequestParam(value = "orderBy", defaultValue = "") orderBy: String
    ): String {
        val queryWrapper = QueryWrapper<GoodsOrder>()
        if (orderBy == "") {
            queryWrapper.orderByDesc("buy_time")   // 按照时间降序排序
        } else {
            queryWrapper.orderByDesc(orderBy)   // 按照给定的字段降序排序
        }
        val goodsList = goodsOrderMapper.selectList(queryWrapper)
        val gson = GsonBuilder().create()
        return gson.toJson(goodsList)
    }


    @PostMapping("/api/updateGoodsOrder")
    fun updateGoodsOrder(
        @RequestBody data: String
    ): String {

        val gson = GsonBuilder().setDateFormat(dateFormat).create()
        val goodsOrder = gson.fromJson(data, GoodsOrder::class.java)
        println(goodsOrder.id)
        val res = goodsOrderMapper.updateById(goodsOrder)
        return res.toString()
    }

    @PostMapping("/api/deleteGoodsOrder")
    fun deleteGoodsOrder(
        @RequestParam("id") id: String
    ): String {
        println(id)
        return goodsOrderMapper.deleteById(id).toString()
    }

    @GetMapping("/api/getGoodsOrder")
    fun getGoodsOrder(
        @RequestParam("id") id: String
    ): String {
        val goodsOrder = goodsOrderMapper.selectById(id)
        val gson = GsonBuilder().create()
        return gson.toJson(goodsOrder)
    }

    class ResponseWithGoodsOrderListWithGoods : Response() {
        lateinit var goodsOrderList: ArrayList<GoodsOrder>
        lateinit var goodsList: ArrayList<Goods>
    }

    /**
     * 获取用户的订单列表
     * @param buyerId 用户id
     * @return 订单列表和对应的商品列表
     */
    @GetMapping("/api/getBuyerGoodsOrder")
    fun getBuyerGoodsOrder(
        @RequestParam("buyerId") buyerId: Int
    ): String? {

        val res = ResponseWithGoodsOrderListWithGoods()

        // 获取订单列表
        val queryWrapper = QueryWrapper<GoodsOrder>()
        queryWrapper.eq("buyer_id", buyerId).orderByDesc("buy_time")
        res.goodsOrderList = goodsOrderMapper.selectList(queryWrapper) as ArrayList<GoodsOrder>

        // 获取对应的商品列表
        res.goodsList = ArrayList()
        for (goodsOrder in res.goodsOrderList) {
            val goods = goodsMapper.selectById(goodsOrder.goodsId)
            if (goods != null) {
//                如果商品列表中没有该商品，则
                val findGoods = res.goodsList.find { it.id == goods.id }
                if (findGoods == null) {
                    res.goodsList.add(goods)
                }
            }
        }
        res.result = "ok"
        val gson = GsonBuilder().create()
        return gson.toJson(res)
    }

    class SellerOrderListResponse : Response() {
        lateinit var goodsOrderList: ArrayList<GoodsOrder>
        lateinit var goodsList: ArrayList<Goods>
        lateinit var userList: ArrayList<User>
    }

    @GetMapping("/api/getSellerOrderList")
    fun getSellerOrderList(
        @RequestParam("sellerId") sellerId: Int
    ): String? {

        val res = SellerOrderListResponse()

        // 获取该卖家的所有上架商品
        val goodsWrapper = QueryWrapper<Goods>()
        goodsWrapper.eq("seller_id", sellerId)
        val goodsList = goodsMapper.selectList(goodsWrapper)
        res.goodsList = goodsList as ArrayList<Goods>

//        获取订单
        val queryWrapper = QueryWrapper<GoodsOrder>()
        queryWrapper.orderByDesc("buy_time")
        val orderAllList = goodsOrderMapper.selectList(queryWrapper)
        val orderList = orderAllList.filter { goods -> goodsList.find { it.id == goods.goodsId } != null }
        res.goodsOrderList = orderList as ArrayList<GoodsOrder>

//      获取用户
        val userWrapper = QueryWrapper<User>()
        for (order in orderList) {
            userWrapper.eq("id", order.buyerId)
            userWrapper.or()
        }
        val userList = userMapper.selectList(userWrapper)
//        解密用户信息
        for (user in userList) {
            user.username = safeService.des3Decrypt(user.username!!, System.getenv("RRS_USER_USERNAME_KEY"))
        }
        res.userList = userList as ArrayList<User>

        val gson = GsonBuilder().create()
        return gson.toJson(res)
    }

    /**
     * 更新订单状态API
     * @param id 订单id
     * @param to 要更新为什么状态
     * @param expressNum 发货时的快递单号
     * @return result: ok(更新成功)
     */
    @PostMapping("/api/updateOrderStatus")
    fun updateOrderStatus(
        @RequestParam(value = "id") id: String,
        @RequestParam(value = "to") to: Int,
        @RequestParam(value = "expressNum", defaultValue = "") expressNum: String,
    ): String? {

        val wrapper = QueryWrapper<GoodsOrder>()
        wrapper.eq("id", id)

        val order = GoodsOrder()
        order.status = to

        when (to) {
            //        如提交发货，则同步提交单号，更新发货时间
            1 -> {
                order.expressNum = expressNum
                order.shippingTime = Timestamp.from(Instant.now())
            }
            //        如确认收货，则更新完成时间
            2 -> {
                order.finishTime = Timestamp.from(Instant.now())
            }
        }

        goodsOrderMapper.update(order, wrapper)

        val res = Response()

        res.result = "ok"
        val gson = GsonBuilder().create()

        return gson.toJson(res)
    }
}